const express=require('express');
const router = express.Router(); 
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.urlencoded({extended:false}))
const jwt = require('../../pem/jwt.js')
const userModel = require('../../model/userModel.js')
const util = require('../../utils/common.js')
const updataToken = function(conditions,token){
	userModel.findOneAndUpdate(conditions,{token:token},(err,doc)=>{
		if(err){
			console.log('token更新失败');
			return
		}
		console.log('token更新成功');
	})
}
router.post('/', (req, res)=> {
	let data = {
		user:req.body.user
	}
	let findResult = util.findData(userModel,data)
	findResult.then(result=>{
		if(result.length){
			let token=result[0].token
			let conditions = {user:req.body.user}
			if(result[0].pwd==req.body.pwd){
				if(token){
					let verifyResult = new jwt(token).verifyToken()
					if (verifyResult.name == 'TokenExpiredError'||verifyResult.name == 'JsonWebTokenError') {
						token = new jwt(result[0]).generateToken()
						updataToken(conditions,token)
					} 
				}else{
					token = new jwt(result[0]).generateToken()
					updataToken(conditions,token)
				}
				res.send({
					'code':'200',
					'msg':'登录成功',
					'data':{
						'token':token
					}
				})
			}else{
				res.send({
					'code':'200',
					'msg':'用户或密码错误'
				})
			}
		}else{
			res.send({
				'code':'200',
				'msg':'用户或密码错误'
			})
		}
	})
});

module.exports = router;